package kuangshen.start;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 文件下载实现多线程
 * 使用Runnable实现
 */
public class RunnableTest implements Runnable{

    private String url;
    private String name;


    public RunnableTest(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downLoader(url,name);
        System.out.println("文件<"+name+">下载完成");
    }

    public static void main(String[] args) {
        String url = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1963304009,2816364381&fm=26&gp=0.jpg";
        String name = "";
        RunnableTest runnableTest1 = new RunnableTest(url,"1.jpg");
        RunnableTest runnableTest2 = new RunnableTest(url,"2.jpg");
        RunnableTest runnableTest3 = new RunnableTest(url,"3.jpg");
        RunnableTest runnableTest4 = new RunnableTest(url,"4.jpg");
        Thread thread1 = new Thread(runnableTest1);
        Thread thread2 = new Thread(runnableTest2);
        Thread thread3 = new Thread(runnableTest3);
        Thread thread4 = new Thread(runnableTest4);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

class WebDownLoader{
    public void downLoader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("网络连接异常");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("本地下载异常");
        }
    }
}